<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" class="add" @click="addbtn">添加分类</el-button>
      <tree-table
        :data="categories"
        :columns="columns"
        :selection-type="false"
        show-index
        index-text="#"
        :expand-type="false"
      >
        <template slot="isok" slot-scope="scope">
          <i
            v-if="!scope.row.cat_deleted"
            class="el-icon-success"
            style="color: green"
          ></i>
          <i v-else class="el-icon-error" style="color: red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="do" slot-scope="scope">
          <el-button type="primary" class="el-icon-edit-outline" @click="edit(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            class="el-icon-delete-solid"
            @click="del(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="pageSizes"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tol"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="addDialogFormVisible" @close="closeDialog">
      <el-form
        :model="addform"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addform.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="parentList"
            :props="{ 
              expandTrigger: 'click',
              value:'cat_id',
              label:'cat_name',
              children:'children'
             }"
            @change="parentChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addfl"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 编辑分类 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogFormVisible" @close="closeDialog">
      <el-form
        :model="editForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSub"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      categories: [],
      queryInfo: {
        type: "",
        pagenum: 1,
        pagesize: 5,
      },
      pageSizes:[5,10],
      tol: 0,
      //为table指定列的定义
      columns: [
        { label: "分类名称", prop: "cat_name" },
        { label: "是否有效", type: "template", template: "isok" },
        { label: "排序", type: "template", template: "order" },
        { label: "操作", type: "template", template: "do" },
      ],
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      addform: {
        cat_pid: 0,
        cat_name: "",
        cat_level: 0,
      },
      rules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 1, max: 8, message: "长度在 1~8 个字符", trigger: "blur" },
        ],
      },
      parentList: [],
      selectedKeys: [],
      editForm:{}
    };
  },
  created() {
    this.getCategs();
  },
  methods: {
    async getCategs() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return (this.$message.erro = "获取商品分类失败");
      }
      this.categories = res.data.result;
      this.tol = res.data.total;
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getCategs();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getCategs();
    },
    addbtn() {
      this.addDialogFormVisible = true;
      this.getParentlist();
    },
    async getParentlist() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父类分类失败");
      }
      this.parentList = res.data;
    },
    parentChange(val){
      this.selectedKeys = val;
      if(this.selectedKeys.length > 0){
        this.addform.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
        this.addform.cat_level = this.selectedKeys.length;
      }
    },
    async addfl(){
      this.$refs.ruleForm.validate(async valid => {
        if(!valid) return
        const { data:res } = await this.$http.post('categories',this.addform)
      if (res.meta.status !== 201) {
        return this.$message.error("添加分类失败");
      }
      this.$message.success("添加分类成功");
      this.getCategs();
      this.addDialogFormVisible = false;
      })
    },
    closeDialog(){
      this.$refs.ruleForm.resetFields();
      this.selectedKeys = [];
      this.addform.cat_pid = 0;
      this.addform.cat_level = 0;
    },
    async edit(id){
      this.editDialogFormVisible = true;
      const { data:res } = await this.$http.get('categories/'+id);
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类失败");
      }
      this.editForm = res.data;
    },
    async editSub(){
      const { data:res } = await this.$http.put('categories/'+this.editForm.cat_id,{
        cat_name: this.editForm.cat_name 
      });
      if (res.meta.status !== 200) {
        return this.$message.error("编辑失败");
      }
      this.$message.success("编辑成功");
      this.editDialogFormVisible = false;
      this.getCategs();
    },
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`categories/${id}`);
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.$message.success("删除成功");
          this.getCategs();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style scoped>
.add {
  margin-bottom: 20px;
}
.el-cascader {
  width: 100%;
}
.el-cascader-menu__wrap{
  height: 300px;
}
</style>